var express = require('express');
var router = express.Router();
const UserModel = require('../../db/modules/UderModel');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const {secret} = require('../../db/config/config');

router.post('/login',(req,res)=>{
    //查询用户名和密码
    let  {username,password} = req.body;
    //查询数据库
    UserModel.findOne({username:username,password:md5(password)}).then((data)=>{
        if(!data){
            res.json({
                code: '2001',
                msg:'用户名或密码错误',
                data:null
            })
        }
        let token = jwt.sign({
            username:data.username,
            _id : data._id
        },secret,{
            expiresIn: 60 *60 * 24 * 7
        })
        res.json({
            code:'0000',
            msg:'登陆成功',
            data:token
        })
        res.render('success',{msg:'登陆成功',url:'/account'});
    }).catch((err)=>{
        res.json({
            code: '2001',
            msg:'数据库读取失败',
            data:null
        })
    })
})
//退出登录
router.post('/logout',(req,res)=>{
    req.session.destroy(()=>{
        res.render('success',{msg:"退出成功",url:'/login'})
    })
});

module.exports = router;